<template>
  <el-header style="margin-bottom: 40px">
    <TopBar
    />
  </el-header>
  <div class="account-page">
    <!-- 顶部个人信息区域 -->
    <div class="profile-header">
      <div>
        <el-avatar class="avatar" size="large" :src="imageUrl" @click="clickAvatar"/>
      </div>
      <div class="name-header">{{ accountInfo.username }}</div>
      <div @click="changeButtonVisibility(true)" class="edit" v-if="!buttonVisibility">编辑</div>
    </div>

    <!-- Tabs 切换 -->
    <el-tabs v-model="activeTab" class="tabs-container">
      <!-- 账号信息 -->
      <el-tab-pane label="账号信息" name="accountInfo">
        <el-form ref="accountFormRef" label-width="150px" :model="accountInfo" label-position="left" :rules="rules"
                 :disabled="!buttonVisibility">

          <!-- 手机号 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="accountInfo.email" placeholder="请输入邮箱" clearable/>
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="accountInfo.phone" placeholder="请输入手机号" clearable/>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input v-model="accountInfo.password" type="password" show-password
                      placeholder="密码不展示，想修改密码请输入密码" clearable/>
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="accountInfo.confirmPassword" type="password" show-password placeholder="请输入密码"
                      clearable/>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item>
            <div class="accountInfoButton" v-if="buttonVisibility">
              <el-button type="primary" @click="saveAccountInfo" :loading="fullscreenLoading">保存</el-button>
              <el-button type="info" @click="cancelAccountInfo">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 基础信息 -->
      <el-tab-pane label="基础信息" name="basicInfo">
        <el-form ref="userFormRef" label-width="100px" :model="userInfo" :disabled="!buttonVisibility" :inline="true">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" placeholder="请输入用户名" clearable/>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="年龄">
                <el-input-number v-model="userInfo.age" placeholder="请输入年龄" min="0" style="width: 250px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别">
                <el-radio-group v-model="userInfo.sex" placeholder="请选择性别" size="large">
                  <el-radio-button value="1">男</el-radio-button>
                  <el-radio-button value="0">女</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="学校">
            <el-input v-model="userInfo.school" placeholder="请输入学校" clearable/>
          </el-form-item>

          <el-form-item label="爱好">
            <el-input v-model="userInfo.love" placeholder="请选输入爱好" clearable/>
          </el-form-item>

          <el-form-item label="个人简历" class="personText">
            <el-input v-model="userInfo.resume" type="textarea" placeholder="请填写个人简历" clearable/>
          </el-form-item>

          <el-form-item>
            <div class="userInfoButton" v-if="buttonVisibility">
              <el-button type="primary" @click="saveUserInfo">保存</el-button>
              <el-button type="info" @click="cancelUserInfo">取消</el-button>
            </div>

          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <cope-dialog :dialog-visible="dialogVisible" @change-dialog-visible="clickCancel" @change-submit-img="clickConfirm"
                 :img="imageUrl">

    </cope-dialog>

    <el-dialog v-model="isShowEmailDialog" title="获取验证码">
      <el-form ref="emailForm" :model="accountInfo" :rules="emailFormRules">
        <div style="display: flex; flex-direction: row; align-items: center; width: 100%; justify-content: space-between; padding: 20px">
          <el-form-item prop="emailCode" class="auto" style="width: auto;" label="验证码">
            <el-input
                size="large"
                class="input-wid"
                v-model="accountInfo.emailCode"
                placeholder="请输入邮箱验证码"
            ></el-input>
          </el-form-item>
          <div class="w-18px"></div>
          <el-button size="large" :disabled="isCounting" :loading="smsLoading" @click="handleSms" type="primary">
            {{ label }}
          </el-button>
        </div>
      </el-form>

      <template #footer>
       <div class="button-container">
         <el-button @click="isShowEmailDialog = false">取消</el-button>
         <el-button type="primary" @click="validateAndSendEmail">
           确定
         </el-button>
       </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import TopBar from "@/components/topBar.vue";
import {updateUser, getUserInfo} from "../api/setting/setting.js"
import useUserStore from "../stores/useUserStore.js"
import CopeDialog from "@/components/copeDialog.vue";
import {useRoute, useRouter} from "vue-router";
import useSmsCode from "@/utils/useSmsCode.js"
import {REGEXP_EMAIL} from "@/utils/regex.js"

const router = useRouter()
const route = useRoute()
const isShowEmailDialog = ref(false)
let {label, isCounting, loading: smsLoading, getSmsCode} = useSmsCode();
const sourceEmail= ref("")
const activeTab = ref('accountInfo')
const accountFormRef = ref(null)
const dialogVisible = ref(false)

const fullscreenLoading = ref(false)
const buttonVisibility = ref(false)
const userInfo = ref({
  name: '',
  age: "",
  sex: "",
  school: "",
  love: "",
  resume: "",
  username: ""
})

const accountInfo = ref({
  username: '',
  email: '',
  merchant: '',
  phone: '',
  password: '',
  confirmPassword: '',
  emailCode: ''
})


const emailFormRules = {
  emailCode: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
  ]
}

const emailForm = ref(null)

const validateAndSendEmail = () => {
  emailForm.value.validate(valid => {
    if (valid) {
      sendEmail()
    } else {
      console.log("表单校验失败")
    }
  })
}

const sendEmail = () => {
  updateAccountInfo()
  isShowEmailDialog.value = false
}
const handleSms = () => {
  getSmsCode(accountInfo.value.email)
}

const changeButtonVisibility = (visibility) => {
  buttonVisibility.value = visibility
}

const validateConfirmPassword = (rule, value, callback) => {
  if (accountInfo.value.password && !value) {
    callback(new Error("请输入确认密码"));
  } else if (value && value !== accountInfo.value.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const validateConfirmEmail = (rule, value, callback) => {
  if (!REGEXP_EMAIL.test(value)) {
    callback(new Error("请输入正确格式的邮箱"));
  }else {
    callback();
  }
};

const rules = {
  confirmPassword: [{validator: validateConfirmPassword, trigger: "blur"}],
  email: [{validator: validateConfirmEmail, trigger: "blur"}]
};

// 页面挂载时根据当前路由设置状态
onMounted(() => {
  activeTab.value = route.query.type
  getInfo()
})
const getInfo = async () => {
  const res = await getUserInfo()
  if (res.data.code === 200) {
// 只复制 userInfo 中已有的属性对应的值
    Object.keys(userInfo.value).forEach(key => {
      if (key in res.data.result) {
        if (key === "sex"){
          userInfo.value[key] = res.data.result[key] + "";
        }else {
          userInfo.value[key] = res.data.result[key];
        }
      }else {
        userInfo.value[key] = ""
      }
    });

    // 只复制 userInfo 中已有的属性对应的值
    Object.keys(accountInfo.value).forEach(key => {
      if (key in res.data.result) {
        accountInfo.value[key] = res.data.result[key];
      }else {
        accountInfo.value[key] = ""
      }
    });
    sourceEmail.value = res.data.result.email
    imageUrl.value = res.data.result.userPhoto
  } else {
    ElMessage.success('获取数据失败')
  }
}
watch(() => activeTab.value, (newValue) => {
  if (newValue === "accountInfo" || newValue == null) {
    activeTab.value = 'accountInfo'
    router.push({path: '/setting', query: {type: "accountInfo"}})
  } else if (newValue === "basicInfo") {
    activeTab.value = 'basicInfo'
    router.push({path: '/setting', query: {type: "basicInfo"}})
  }
})



const imageUrl = ref("");

const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

// 处理上传成功
const handleSuccess = (response, file) => {
  console.log("上传成功", response, file);
  if (file.raw) {
    imageUrl.value = URL.createObjectURL(file.raw); // 生成本地预览 URL
  } else if (response && response.url) {
    imageUrl.value = response.url; // API 返回的图片 URL
  }
};
const saveAccountInfo = async () => {
  accountFormRef.value.validate(async valid => {
    if (valid) {
      if (useUserStore().email !== accountInfo.value.email) {
        isShowEmailDialog.value = true
      } else {
        await updateAccountInfo()
      }
    } else {
      console.log("表单校验失败")
    }
  })
}

const updateAccountInfo = async () => {
  fullscreenLoading.value = true
  try {
    const res = await updateUser(accountInfo.value)
    fullscreenLoading.value = false
    if (res.data.code === 200) {
      ElMessage.success("修改成功")
      buttonVisibility.value = false
      await useUserStore().getInfo()
      await getInfo()
    } else {
      ElMessage.error("修改失败")
    }
  }catch (e){
    fullscreenLoading.value = false
  }
}
const cancelAccountInfo = () => {
  buttonVisibility.value = false
}
const saveUserInfo = async () => {
  fullscreenLoading.value = true
  try {
    const res = await updateUser(userInfo.value)
    fullscreenLoading.value = true
    if (res.data.code === 200) {
      buttonVisibility.value = false
      ElMessage.success("修改成功")
    } else {
      ElMessage.error("修改失败")
    }
  }catch (e){
    fullscreenLoading.value = true
  }

}
const cancelUserInfo = () => {
  buttonVisibility.value = false
}

const clickAvatar = () => {
  dialogVisible.value = true

}

const clickCancel = (value) => {
  dialogVisible.value = value
}
//
const clickConfirm = async (value) => {
  imageUrl.value = value
  const res = await updateUser({
    userPhoto: imageUrl.value
  })
  if (res.data.code === 200) {
    await useUserStore().getInfo()
    ElMessage.success('头像更换成功')
    dialogVisible.value = false
  } else {
    ElMessage.error('头像更换失败')
  }
}
</script>

<style scoped>
.account-page {
  width: 1078px;
  border: 2px solid #827c7c47;
  margin-left: calc(50% - 540px);
  padding: 20px;
  background-color: #fff;
  margin-top: 40px;
}

.profile-header {
  position: relative;
  display: flex;
  align-items: center;
  margin: 20px 0 20px 0;
  justify-items: center;

}

.edit {
  position: absolute;
  right: 20px;
  color: #6f7779;;
}

.name-header {
  font-size: 25px;
  font-weight: 700;
  color: #363434;
}

.avatar {
  margin-right: 16px;
}

.tabs-container {
  margin-top: 20px;
}

.accountInfoButton, .userInfoButton {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-items: center;
  justify-content: space-between;
  padding: 0 80px;
  width: 100%;
}

.accountInfoButton button, .userInfoButton button {
  width: 100px;
  height: 40px;
}

.uploaded-image {
  position: relative;
  display: inline-block;
}

.preview-image {
  display: block;
  width: 100%;
  height: auto;
}

/* 删除图标初始状态：模糊且透明 */
.delete-icon {
  position: absolute;
  top: calc(50% - 20px);
  right: calc(50% - 20px);
  filter: blur(4px);
  opacity: 1;
  transition: filter 0.5s ease, opacity 0.5s ease;
  cursor: pointer;
}

/* 鼠标悬停时，删除图标变清晰并显示 */
.image-wrapper:hover .delete-icon {
  filter: blur(0);
  opacity: 1;
}
.input-wid{
  width: 250px;
}

.button-container button{
  width: 100px;
  height: 35px;
}
:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

:deep(.el-form-item__label) {
  font-size: 20px;
}

:deep(.el-select__wrapper) {
  height: 45px;
}

:deep(.el-input__inner) {
  height: 45px;
}

:deep(.el-form-item) {
  display: flex;
  justify-items: center;
  align-items: center;
  flex-direction: row;
}

:deep(.el-tabs__item) {
  font-size: 16px;
}

:deep(.is-active) {
  font-weight: 600;
}

:deep(.el-date-editor) {
  width: 100%;
  height: 45px;
}

:deep(.el-textarea__inner) {
  min-height: 80px !important;
}

:deep(.el-input__inner), :deep(.el-textarea__inner), :deep(.el-select__wrapper) {
  font-size: 16px;
}

</style>
